package com.xnfh.home.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.xnfh.framework.base.BaseFragment
import com.xnfh.framework.base.BaseStateObserver
import com.xnfh.framework.bean.HomeBannerBean
import com.xnfh.framework.bean.HomeTongjiBean
import com.xnfh.framework.bean.WeatherDetailBean
import com.xnfh.framework.log.LogUtil
import com.xnfh.framework.toast.TipsToast
import com.xnfh.framework.utils.PermissionUtils
import com.xnfh.home.R
import com.xnfh.home.adapter.ImageAdapter
import com.xnfh.home.databinding.FragmentHomeLayoutBinding
import com.xnfh.home.imp.AMapLocationImp
import com.xnfh.home.ui.activity.MessageActivity
import com.xnfh.home.ui.activity.ProductIntroduceActivity
import com.xnfh.home.utils.ChartHelper
import com.xnfh.home.utils.LocationUtil
import com.xnfh.home.utils.WeatherHelper
import com.xnfh.home.viewmodel.HomeViewModel
import com.youth.banner.indicator.CircleIndicator

/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/11/8 14:34
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/11/8 14:34
 * @UpdateRemark: 更新说明
 */
class HomeFragment : BaseFragment<FragmentHomeLayoutBinding>(),View.OnClickListener {
    override fun getLayoutID(): Int = R.layout.fragment_home_layout
    private lateinit var viewModel: HomeViewModel

    override fun initView(view: View, savedInstanceState: Bundle?) {
        mBind.homeIconClub.setOnClickListener(this)
        mBind.homeIconMessage.setOnClickListener(this)
        mBind.homeIconFeedback.setOnClickListener(this)
        mBind.homeIconProduct.setOnClickListener(this)
        mBind.homeRefresh.setOnRefreshListener {
            viewModel.requestTodayMessage()
            viewModel.requestTj()
            viewModel.requestNoReadNum()
        }
        view.postDelayed({
            //请求权限
            PermissionUtils.openGPS(requireActivity(), object : PermissionUtils.PermissionImp {
                override fun onSuccess(allGranted: Boolean) {
                    LogUtil.e("onSuccess 开启成功了")
                    //请求定位之后，开启定位获取经纬度
                    LocationUtil.startLocation()
                }

                override fun onField() {
                    super.onField()
                    TipsToast.showTips(R.string.str_no_address_permission_error_tips)
                    mBind.homeRefresh.autoRefresh()
                    LogUtil.e("onSuccess 开启权限失败了")
                }
            })
            //开启读写权限
            PermissionUtils.requestPermissions(requireActivity())
        }, 100)
        //定位完成请求接口
        LocationUtil.initLocation(requireActivity(), object : AMapLocationImp {
            override fun onLocationChanged() {
                LogUtil.e("onLocationChanged 开启成功了")
                //如果定位成功就自动刷新接口
                mBind.homeRefresh.autoRefresh()
                //只有定位成功才能刷新天气接口，必须传入经纬度
                viewModel.requestWeather()
            }

            override fun onLocationError() {
                TipsToast.showTips(R.string.str_no_address_permission_tips)
                //如果定位失败就自动刷新接口
                mBind.homeRefresh.autoRefresh()
            }
        })
    }

    override fun onClick(v: View?) {
        when(v){
            mBind.homeIconMessage ->{
                val bundle = Bundle()
                bundle.putInt("type", 1)//消息
                MessageActivity.start(requireContext(), bundle)
            }
            mBind.homeIconFeedback ->{
                val bundle = Bundle()
                bundle.putInt("type", 2)//反馈
                MessageActivity.start(requireContext(), bundle)
            }
            mBind.homeIconClub ->{
                val bundle = Bundle()
                bundle.putInt("type", 3)//俱乐部
                MessageActivity.start(requireContext(), bundle)
            }
            mBind.homeIconProduct ->{
                ProductIntroduceActivity.start(requireContext())
            }
        }
    }

    override fun observe() {
        viewModel = HomeViewModel()
        //天气数据
        viewModel.weatherRes.observe(this, object : BaseStateObserver<WeatherDetailBean>() {
            @SuppressLint("SetTextI18n")
            override fun getRespDataSuccess(it: WeatherDetailBean) {
                super.getRespDataSuccess(it)
                if(it.winddir == null){
                    //就那其中一个数据做判断，如果是null就不展示，主要是应对测试环境不返回数据
                    return
                }
                mBind.homeWeatherNumber.text = it.temp
                mBind.homeWeatherType.text = "℃\n${it.condition}"
                mBind.homeWeatherHigLow.text =
                    "${getString(R.string.temp_max)} ${it.maxTemp}  ${getString(R.string.temp_min)} ${it.minTemp}"
                mBind.homeHumidness.text = "${getString(R.string.str_humidness)}${it.humidity}%"
                mBind.homeWindDirection.text = "${
                    WeatherHelper.getWinddirByCode(
                        requireContext(),
                        it.winddir
                    )
                }${getString(R.string.str_ji)}"
                WeatherHelper.getIconByCondition(it.condition).let {
                    mBind.homeWeatherImg.setImageResource(it!!)
                }
            }
        })
        //今日头条
        viewModel.bannerBean.observe(this, object : BaseStateObserver<List<HomeBannerBean>>() {
            override fun getRespDataSuccess(it: List<HomeBannerBean>) {
                super.getRespDataSuccess(it)
                if(it.isEmpty()){
                    mBind.homeJrttLinear.visibility = View.GONE
                    return
                }else{
                    mBind.homeJrttLinear.visibility = View.VISIBLE
                }
                mBind.homeBanner.addBannerLifecycleObserver(this@HomeFragment)
                    .setAdapter(ImageAdapter(it)).indicator = CircleIndicator(requireContext())
                mBind.homeRefresh.finishRefresh()
            }
        })
        //展示统计柱形图
        viewModel.tjBean.observe(this, object : BaseStateObserver<HomeTongjiBean>() {
            override fun getRespDataSuccess(it: HomeTongjiBean) {
                super.getRespDataSuccess(it)
                ChartHelper.setChart(requireContext(), mBind.homeBarchart, it)
                mBind.homeRefresh.finishRefresh()
            }
        })
        //未读消息数量
        viewModel.noReadNum.observe(this, object : BaseStateObserver<Int>() {
            override fun getRespDataSuccess(it: Int) {
                super.getRespDataSuccess(it)
                mBind.homeNoReadMessage.text = it.toString()
                mBind.homeNoReadMessage.visibility = if (it > 0) {
                    View.VISIBLE
                } else {
                    View.GONE
                }
                mBind.homeRefresh.finishRefresh()
            }
        })
    }


}